// 分类浏览页面
import React, { useState } from 'react';
import { Pagination, Input, Row, Col, Image, Card, Divider, Layout, Spin} from 'antd';
import '../css/App.css';
import axios from 'axios';
import {Link, Route, useParams} from 'react-router-dom';
import TopMenu from '../component/menu/top-menu'
import LeftMenu from '../component/menu/left-menu';

interface List{
  author: string,
  bookId: number,
  categoryName: string,
  chapterStatus: string,
  coverImg: string,
  desc: string,
  title:string,
  word: string,
}

export default function CategoryPage() {

  const params = useParams();
  console.log("Router.data:", params.id);
  const bookid:number = Number(params.id);

    // home booklist data mock
    const bookList:List[] = [{
      "author": "皇甫奇",
      "bookId": 30750,
      "categoryName": "玄幻小说",
      "chapterStatus": "END",
      "coverImg": "/file/group1/book/92e022b5-6c36-4851-a031-fa6aa8f2bd7c.jpg",
      "desc": " 天地二魂常在外，唯有命魂住其身。命魂住胎，衍化七魄。每个人的生命，都是从命魂住胎开始的，但方云的生命，却是从终结的那一刻开始的……真正的皇族，不是来自于血统的传承，而是来自命格和灵魂层面的高贵！ ",
      "title": "大周皇族",
      "word": "689万字"
    },
    {
      "author": "六器",
      "bookId": 30752,
      "categoryName": "网游小说",
      "chapterStatus": "END",
      "coverImg": "/file/group1/book/59b948c8-5098-40a6-8ea0-76ea6241ceae.jpg",
      "desc": " 一场热血的骑士战争。踏上骑士之路，无法回头，亡灵骑士，红莲骑士，深渊骑士，魔神骑士，远古骑士，末日骑士。网游《远古》，霸者称雄，雄者为尊，强者为王，树欲静而风不止，骑士，如何战斗。 ",
      "title": "网游之全职大骑士",
      "word": "179万字"
    },
    {
      "author": "庄毕凡",
      "bookId": 30765,
      "categoryName": "网游小说",
      "chapterStatus": "END",
      "coverImg": "/file/group1/book/0725ef78-c163-4c08-beda-8d67c91646db.jpg",
      "desc": " 网络游戏中的仓库小号，却意外的穿越到了异界。他不但带来了无数极品材料，还精通几乎所有的生活技能，最可怕的是，这家伙同时还是一个空前绝后的魔法天才！ ",
      "title": "异界全职业大师",
      "word": "510万字"
    },
    {
      "author": "说梦者",
      "bookId": 30861,
      "categoryName": "修真小说",
      "chapterStatus": "SERIALIZE",
      "coverImg": "/file/group1/book/b28b1429-46c9-4deb-b516-26dd1ac631b9.jpg",
      "desc": " 妖魔中的至高无上者，名为“大圣”。少年走出山村，踏遍天下，一步步跨入传说中，成为神话。 ",
      "title": "大圣传",
      "word": "472万字"
    },
    {
      "author": "塞外流云",
      "bookId": 30872,
      "categoryName": "历史小说",
      "chapterStatus": "END",
      "coverImg": "/file/group1/book/e44b94f6-66a4-45c7-b999-eb2d2712a90a.jpg",
      "desc": " 男儿何伤？拒地一呼吾往矣，万里摇肢动骨。若新生，把当时、一桩大义，拆开收合。当平凡宅男穿越成为康熙帝的十四子爱新觉罗胤祯后，大清便风起云涌。且看康熙翻云覆雨，且看十四强势翻转！为争夺皇位，胤祯强势出手，强势到康熙和一众王公大臣对他爱恨交加，却欲罢不能。一众皇子对他恨之入骨，手段尽出，却也只能打掉牙和血吞，面对他还要强颜欢笑。九龙夺嫡，阳谋和阴谋的碰撞。 ",
      "title": "大清弊主",
      "word": "184万字"
    },
    {
      "author": "河马散人",
      "bookId": 30928,
      "categoryName": "历史小说",
      "chapterStatus": "END",
      "coverImg": "/file/group1/book/2d4d082a-c19d-4a47-9f34-dab4dc484960.jpg",
      "desc": " 那一年，小胡子登上了中央广场的演讲台，高举着单臂，煽动人心的演讲中多了这样一段。“在东方，有一个人，建立了一个全新的亚洲秩序！今天，应该轮到我们骄傲伟大的德意志，用鲜血和生命！去建立一个全新世界秩序！并捍卫它直至世界末日！”那天，华尔街时报写下了这样一段话：“军人的时代......或许明天又将到来！”*****或许，这是本不错的历史军事小说。 ",
      "title": "辛亥大英雄",
      "word": "932万字"
    },
    {
      "author": "镔铁",
      "bookId": 30942,
      "categoryName": "都市小说",
      "chapterStatus": "END",
      "coverImg": "/file/group1/book/b8fe0cec-dc87-4e10-9fb1-ba54de48028e.jpg",
      "desc": " 明星可以成为总统，那明星为何不能成为大亨？！重生在香港电影的黄金年代，从跑龙套开始，再到明星，歌星，大亨，一步一个脚印，见证了港片的辉煌。因为爱电影，所以希望香港电影能有崭新的未来，陈笑棠凭借翻云覆雨的手段，能否扭转这样的乾坤吗？周星池，周闰发，梁超伟，林清霞，赵亚芝，翁美菱这些光环笼罩下的巨星，各自又有怎样的故事？进入本书，带你进入一个璀璨的电影年代－－－－！ ",
      "title": "电影大亨",
      "word": "375万字"
    }];
    const [BookList,SetBookList] = useState(bookList);

    // pageable data
    let Total:number = 100;let page:number = 1;
    const [Page,SetPage] = useState(page);let pageSize:number =10;
    const [PageSize,SetPageSize] = useState(pageSize);

    //点击推荐
    const OnClickRecommend = () => {
    }
    //点击主页
    const OnClickHome = () => {
      SetPage((oldPage) => {
        return page=1
      });
      SetPageSize((oldPageSize) => {
        return pageSize=10
      });
      console.log("修改后的:",page,PageSize);
      PageOnChange(page,pageSize);
    }

    const requestSuccess:boolean = false;
    const [GetRequestSuccess,SetRequestSuccess] = useState(requestSuccess);
        // 加载时请求
        axios.get('http://yuenov.com:15555/app/open/api/book/getCategoryId', {
          params: {
            categoryId: bookid,
            pageNum: page,
            pageSize: pageSize
          }
        }).then(response=>{
          // 服务器忙碌
          if(response.data.result.code===1009 && !GetRequestSuccess){
            console.log("服务器繁忙");
            setTimeout(HttpRequest, 10000);//重新请求
            return;
          }
          // 请求成功，更新书籍信息
          else if(response.data.result.code===0){
            SetRequestSuccess(true);
            if(response.data.data.list!==[]){
              let NewItems: List[] =[] ;
              response.data.data.recommend.forEach((item: any) => {
                let NewItem: List = {
                  author: item.author,
                  bookId: item.bookId,
                  categoryName: item.categoryName,
                  chapterStatus: item.chapterStatus,
                  coverImg: item.coverImg,
                  desc: item.desc,
                  title: item.title,
                  word: item.word
                };
                NewItems.push(NewItem);
              });
              SetBookList((prevState) =>{
                return prevState = NewItems;
              });
            }
          }
        },(error)=>{
            console.log(error)
        })
    
        // 再次请求直到成功
        const isOn: boolean = false;  //是否已经存在请求
        const [IsOn,SetIsOn] = useState(isOn);
        const HttpRequest = ()=>{
          if(IsOn)
            return
          else{
            console.log("已经存在请求");
            SetIsOn(true);
            axios.get('http://yuenov.com:15555/app/open/api/book/getCategoryId', {
              params: {
                categoryId: bookid,
                pageNum: page,
                pageSize: pageSize
              }
            }).then(response=>{
              // 服务器忙碌
              if(response.data.result.code===1009 && !GetRequestSuccess){
                console.log("服务器繁忙");
                setTimeout(HttpRequest, 10000);//重新请求
                return;
              }
              // 请求成功，更新书籍信息
              else if(response.data.result.code===0){
                SetRequestSuccess(true);
                if(response.data.data.list!==[]){
                  let NewItems: List[] =[] ;
                  response.data.data.recommend.forEach((item: any) => {
                    let NewItem: List = {
                      author: item.author,
                      bookId: item.bookId,
                      categoryName: item.categoryName,
                      chapterStatus: item.chapterStatus,
                      coverImg: item.coverImg,
                      desc: item.desc,
                      title: item.title,
                      word: item.word
                    };
                    NewItems.push(NewItem);
                  });
                  SetBookList((prevState) =>{
                    return prevState = NewItems;
                  });
                }
              }
            },(error)=>{
                console.log(error)
            })
          }
        }

    const PageOnChange = (page:number , pageSize:number) => {
      axios.get('http://yuenov.com:15555/app/open/api/book/getCategoryId', {
          params: {
            categoryId: bookid,
            pageNum: page,
            pageSize: pageSize
          }
        }).then((response)=>{
          let NewItems: List[] =[] ;
          if(response.data.result.code===1009){ return}
          else{ response.data.data.list.forEach((item: any) => {
            let NewItem: List = {
              author: item.author,
              bookId: item.bookId,
              categoryName: item.categoryName,
              chapterStatus: item.chapterStatus,
              coverImg: item.coverImg,
              desc: item.desc,
              title: item.title,
              word: item.word
            };
            NewItems.push(NewItem);
          });
          SetBookList(NewItems);}
        });
        SetPage(page);
        SetPageSize(pageSize);
        // console.log("SearchValue",SearchValue);
        // console.log("page",page);
        // console.log("pageSize",pageSize);
    }

    const Jump = (e:any,s:string,id:number) =>{
      console.log("点击书籍：", s,id);
    }

    return (
      <div>
            <Layout>
              <Layout.Header className="header">
                <TopMenu OnClickRecommend={OnClickRecommend} OnClickHome={OnClickHome} />
              </Layout.Header>
              <Layout>
                  <Layout.Sider width={200} className="site-layout-background">
                    <LeftMenu />
                  </Layout.Sider>
                  <Layout.Content className="site-layout-background">
                    {GetRequestSuccess?
                    (<Spin></Spin>):
                    (
                    <>
                    <Row>分类浏览中</Row>
                    {
                    BookList.map((item:List ,key:number) => {
                       return (
                          <>
                          <Divider orientation="left" />
                          {/* <Link to="/book"> */}
                          <Link to={{ pathname: '/book/'+item.bookId}}>
                            <Card title={item.title} bordered={true} onClick={e=>{Jump(e,item.title,item.bookId)}}>
                              <Row>
                                <Col span={4}><Image alt={item.title} height={150} width={100} src={"http://yuenov.com:15555" + item.coverImg} /></Col>
                                  <Col span={2}>作者：{item.author}</Col>
                                    <Col span={4}>简介：{item.desc}</Col>
                               </Row>
                             </Card>
                           </Link>
                          </>);
                        })
                    }
                    <Pagination onChange={PageOnChange} total={Total} />
                    </>
                    )}
                  </Layout.Content>
              </Layout>
            </Layout>
          
      </div>
    )
}

